#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        sort(intervals.begin(), intervals.end(),
            [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; });

        vector<vector<int>> res;
        for (int i = 0; i < intervals.size(); ++i) {
            int begin = intervals[i][0], end = intervals[i][1];
            int j = i + 1;
            for (; j < intervals.size(); ++j) {
                if (intervals[j][0] <= end) {
                    end = max(end, intervals[j][1]);
                }
                else {
                    break;
                }
            }
            i = j - 1;

            res.emplace_back(vector<int>({ begin, end }));
        }

        return res;
    }

    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
        intervals.emplace_back(newInterval);
        sort(intervals.begin(), intervals.end(),
            [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; });
        return merge(intervals);
    }
};